//
//  UserManager.m
//  MiBaoTu
//
//  Created by admin on 16/9/26.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "UserManager.h"
#import "lame.h"
#import "AppDelegate.h"
#import "AFNetworkReachabilityManager.h"

@interface UserManager () {
    NSTimer                 *_timers;
    int                     timeIndex;
}

@end
@implementation UserManager

+ (UserManager *)standerDefult
{
    static UserManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc]init];
    });
    return manager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        timeIndex = 1;
        self.musicArr = [[NSMutableArray alloc]init];
        self.audioPlayerType = AudioPLayerType_Defult;
        self.zhubo_SelectIndex = @"0";
        //是否自动下载
        NSString *isFirstLoadMusic = [[NSUserDefaults standardUserDefaults]objectForKey:@"isFirstLoadMusic"];
        if (isFirstLoadMusic.length == 0) {
            //启动 默认开启
            self.isLoadMusic = YES;
            [[NSUserDefaults standardUserDefaults]setObject:@"isFirstLoadMusic" forKey:@"isFirstLoadMusic"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            
            [[NSUserDefaults standardUserDefaults]setObject:@"isFirstLoadMusic" forKey:@"isLoadMusic"];
            [[NSUserDefaults standardUserDefaults]synchronize];
        } else {
            
            NSString *isLoadMusic = [[NSUserDefaults standardUserDefaults]objectForKey:@"isLoadMusic"];
            if (isLoadMusic.length > 0) {
                self.isLoadMusic = YES;
            } else {
                self.isLoadMusic = NO;
            }
        }
        
        //后台音乐

    }
    return self;
}

- (NSMutableArray *)tempMusicArr
{
    if (!_tempMusicArr) {
        _tempMusicArr = [[NSMutableArray alloc]init];
    }
    return _tempMusicArr;
}

- (NSMutableArray *)collectionMusicArr
{
    if (!_collectionMusicArr) {
        _collectionMusicArr = [[NSMutableArray alloc]init];
    }
    return _collectionMusicArr;
}

- (NSMutableArray *)collectionAlbumArr
{
    if (!_collectionAlbumArr) {
        _collectionAlbumArr = [[NSMutableArray alloc]init];
    }
    return _collectionAlbumArr;
}

- (NSMutableArray *)collectionShowArr
{
    if (!_collectionShowArr) {
        _collectionShowArr = [[NSMutableArray alloc]init];
    }
    return _collectionShowArr;
}

- (NSMutableArray *)collectionMusicTypeArr
{
    if (!_collectionMusicTypeArr) {
        _collectionMusicTypeArr = [[NSMutableArray alloc]init];
    }
    return _collectionMusicTypeArr;
}

- (NSMutableArray *)praiseListArr
{
    if (!_praiseListArr) {
        _praiseListArr = [[NSMutableArray alloc]init];
    }
    return _praiseListArr;
}

- (NSMutableDictionary *)zhuboDic
{
    if (!_zhuboDic) {
        _zhuboDic = [[NSMutableDictionary alloc]init];
    }
    return _zhuboDic;
}

- (NSMutableArray *)qinzixiuArr
{
    if (!_qinzixiuArr) {
        _qinzixiuArr = [[NSMutableArray alloc]init];
    }
    return _qinzixiuArr;
}

- (NSMutableArray *)downingMusicCountArr
{
    if (!_downingMusicCountArr) {
        _downingMusicCountArr = [[NSMutableArray alloc]init];
    }
    return _downingMusicCountArr;
}

- (NSMutableArray *)waitDownMusicCountArr
{
    if (!_waitDownMusicCountArr) {
        _waitDownMusicCountArr = [[NSMutableArray alloc]init];                                  
    }
    return _waitDownMusicCountArr;
}

- (NSMutableArray *)downedMusicArr
{
    if (!_downedMusicArr) {
        _downedMusicArr = [[NSMutableArray alloc]init];
    }
    return _downedMusicArr;
}

- (void)setIsOnlinePlayer:(BOOL)isOnlinePlayer
{
    _isOnlinePlayer = isOnlinePlayer;
}

- (void)setIsLastID:(NSString *)isLastID
{
    _isLastID = isLastID;
}

- (void)setZhubo_SelectIndex:(NSString *)zhubo_SelectIndex
{
    _zhubo_SelectIndex = zhubo_SelectIndex;
}

- (void)setSelectMusicIndex:(NSUInteger)selectMusicIndex
{
    _selectMusicIndex = selectMusicIndex;
}

- (NSMutableArray *)spaceFileArr
{
    if (!_spaceFileArr) {
        _spaceFileArr = [[NSMutableArray alloc]init];
    }
    return _spaceFileArr;
}

#pragma mark - 设置计时器,关闭播放器
- (void)setUpTimer
{
    if (_timers) {
        [_timers invalidate];
        _timers = nil;
    }
    _timers = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onSelectCloseMusicByTimer:) userInfo:nil repeats:YES];
}

- (void)onSelectCloseMusicByTimer:(NSTimer *)timer
{
    NSLog(@"index:%d",timeIndex);
    if (_timerLength == 0) {
        [timer invalidate];
        return;
    }
    
    if (timeIndex >= _timerLength) {
        //发送 禁止播放器播放
        [timer invalidate];
        timer = nil;
        if (self.mainPlayer) {
            [self.mainPlayer pause];
        }
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        
        [UIView animateWithDuration:1.0f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
        
        return;
    }
    
    ++timeIndex;
}


#pragma mark -删除缓存
-(float)folderSizeAtPath{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            folderSize +=[self fileSizeAtPath:absolutePath];
        }
        　　　　　//SDWebImage框架自身计算缓存的实现
//        folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return (folderSize > 0 ? folderSize : 0);
    }
    return 0;
}

-(float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

-(void)clearCache{
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    //数据库
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    filePath = [filePath stringByAppendingPathComponent:@"data.db"];
    if ([fileManager fileExistsAtPath:filePath]) {
        [fileManager removeItemAtPath:filePath error:nil];
    }
    
    //临时数据
    [[UserManager standerDefult].downedMusicArr removeAllObjects];
    [[UserManager standerDefult].downingMusicCountArr removeAllObjects];
    
//    [[SDImageCache sharedImageCache] cleanDisk];
}


#pragma mark - 下载歌曲
- (void)downLoadMusic:(NSDictionary *)_selectCurrentMusicDic
       withRequestArr:(NSArray *)fileIDArr {
    /*
     {
     AudioName = "erge.mp3";
     AudioPath = "/upload/2016-10-9/erge.mp3";
     AudioStatus = 1;
     AuditionNum = 2;
     CreateTime = 0;
     ID = 5;
     LyricPath = "<null>";
     }
     */
    NSString *fileIDShow = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]];
    if (![fileIDArr containsObject:fileIDShow]) {
        //判断是否可以下载
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDowning = NO;
        if (![[UserManager standerDefult].tempMusicArr containsObject:fileIDShow]) {
            isDowning = YES;
        } else {
            NSString *audioName;
            if ([_selectCurrentMusicDic.allKeys containsObject:@"AudioName"]) {
                audioName = [_selectCurrentMusicDic objectForKey:@"AudioName"];
            }
            else if ([_selectCurrentMusicDic.allKeys containsObject:@"ShowTitle"]) {
                audioName = [_selectCurrentMusicDic objectForKey:@"ShowTitle"];
            }
            if ([[audioName componentsSeparatedByString:@"."]count] == 1) {
                audioName = [NSString stringWithFormat:@"%@.mp3",audioName];
            }
            
            if ([audioName isKindOfClass:[NSString class]]) {
                if (audioName.length == 0) {
                    isDowning = NO;
                } else {
                     NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"AudioName"]]];
                    if (![fileManager fileExistsAtPath:filePath]) {
                        isDowning = YES;
                    }
                }
            }
        }
        
        if (isDowning == YES) {
            //加入临时文件,过滤
            [[UserManager standerDefult].tempMusicArr addObject:fileIDShow];
            NSString *urlPath = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_selectCurrentMusicDic objectForKey:@"AudioPath"]];
            
            NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"AudioName"]]];
            
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:NULL];
            }
            
            
            NSString *audioName;
            if ([_selectCurrentMusicDic.allKeys containsObject:@"AudioName"]) {
                audioName = [_selectCurrentMusicDic objectForKey:@"AudioName"];
            }
            else if ([_selectCurrentMusicDic.allKeys containsObject:@"ShowTitle"]) {
                audioName = [_selectCurrentMusicDic objectForKey:@"ShowTitle"];
            }
            if ([[audioName componentsSeparatedByString:@"."]count] == 1) {
                audioName = [NSString stringWithFormat:@"%@.mp3",audioName];
            }
            if ([audioName isKindOfClass:[NSString class]]) {
                if (audioName.length == 0) {
                    return;
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [[DownManager staredInstance]downloadWithUrl:urlPath
                                               withMusicName:audioName
                                                 withMusicID:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]]
                                               withMusicType:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ValueID"]]
                                                withProgress:^(CGFloat progress, NSString *speed, NSString *remainingTime, NSString *writtenSize, NSString *totalSize) {
                                                    
                                                } withStats:^(DownMusicState stats) {
                                                    
                                                }];
            });
        }
    }
}

#pragma mark - 后台音乐播放
- (void)setMusicArr:(NSMutableArray *)musicArr{
    if (!_musicArr) {
        _musicArr = [[NSMutableArray alloc]init];
    }
    
    if (musicArr.count > 0) {
        _musicArr = musicArr;
    }
}

- (void)setMainPlayer:(AVPlayer *)mainPlayer
{
    _mainPlayer = mainPlayer;
    if (mainPlayer) {
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieToEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    } else {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
}

- (void)movieToEnd:(NSNotification *)noty
{
    NSLog(@"播放完毕");
    if (_mainPlayer && _isBackPlay) {
        AVPlayerItem *currentItem = noty.object;
        if (_mainPlayer.currentItem == currentItem) {
            if (_musicArr.count > _selectMusicIndex) {
                ++_selectMusicIndex;
                if (_selectMusicIndex >= _musicArr.count) {
                    _selectMusicIndex = 0;
                }
                
                [_mainPlayer pause];
                
                //自动播放下一首，非播放器页面
                NSURL *urlPath;
                Music *music = [_musicArr objectAtIndex:_selectMusicIndex];
                self.isLastID = [NSString stringWithFormat:@"%@",music.ID];
                if (music.isCacheData) {
                    //读取沙盒已下载的音频
                    NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",music.name]];
                    urlPath = [NSURL fileURLWithPath:filePath];
                } else {
                    urlPath = [NSURL URLWithString:music.urlPath];
                }

                AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
                [_mainPlayer replaceCurrentItemWithPlayerItem:item];
                [_mainPlayer play];
            }
        }
    }
}

//页面点击播放按钮，实现非播放器页面播放功能
- (void)playMusicWithMusicArray:(NSArray *)musciArr
               withCurrentIndex:(NSUInteger)selectIndex
              withMusicPlayType:(MusicPLayType)musicPlayType
{
    NSDictionary *_selectCurrentMusicDic = [musciArr objectAtIndex:selectIndex];
    
    if ([_selectCurrentMusicDic isKindOfClass:[DownMusicModel class]]) {
        DownMusicModel *musicModel = (DownMusicModel *)_selectCurrentMusicDic;
        //数据库模式
        NSString *fileName = [NSString stringWithFormat:@"%@.mp3",musicModel.fileName];
        NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
        BOOL isExist = NO;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            isExist = YES;
        }
        if (self.mainPlayer) {
            //后台存在播放器
            AVPlayer *mainPlayer = (AVPlayer *)self.mainPlayer;
            [mainPlayer pause];
            NSString *urlString = filePath;
            NSURL *urlPath = [NSURL fileURLWithPath:urlString];
            if (!isExist) {
                urlString = [NSString stringWithFormat:@"%@",musicModel.url];
                urlPath = [NSURL URLWithString:urlString];
            }
            AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
            [mainPlayer replaceCurrentItemWithPlayerItem:item];
            [mainPlayer play];
            
            //列入最近播放
            NSString *idStr = [NSString stringWithFormat:@"%@",musicModel.musicID];
            if (idStr.length > 0) {
                FMManageObject *manager = [FMManageObject standerDefault];
                NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                if (arrs.count == 0) {
                    //来吧
                    NSString *name = [NSString stringWithFormat:@"%@",musicModel.fileName];
                    [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@",musicModel.totalSize] withType:[NSString stringWithFormat:@"%@",musicModel.musicType]];
                }
            }
        } else {
            //设置播放
            NSString *urlString = filePath;
            NSURL *urlPath = [NSURL fileURLWithPath:urlString];
            if (!isExist) {
                urlString = [NSString stringWithFormat:@"%@",musicModel.url];
                urlPath = [NSURL URLWithString:urlString];
            }
            AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
            AVPlayer *audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
            [audioPlayer play];
            [self setMainPlayer:audioPlayer];
            
            //列入最近播放
            NSString *idStr = [NSString stringWithFormat:@"%@",musicModel.musicID];
            if (idStr.length > 0) {
                FMManageObject *manager = [FMManageObject standerDefault];
                NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                if (arrs.count == 0) {
                    //来吧
                    NSString *name = [NSString stringWithFormat:@"%@",musicModel.fileName];
                    [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@",musicModel.totalSize] withType:[NSString stringWithFormat:@"%@",musicModel.musicType]];
                }
            }
        }
    } else if ([_selectCurrentMusicDic isKindOfClass:[NSDictionary class]]) {
        if (( [_selectCurrentMusicDic.allKeys containsObject:@"fileID"]&& [_selectCurrentMusicDic.allKeys containsObject:@"fileName"]&& [_selectCurrentMusicDic.allKeys containsObject:@"id"]&& [_selectCurrentMusicDic.allKeys containsObject:@"size"]&& [_selectCurrentMusicDic.allKeys containsObject:@"type"]&& [_selectCurrentMusicDic.allKeys containsObject:@"url"]) ) {
            //数据库模式
            NSString *fileName = [NSString stringWithFormat:@"%@.mp3",[_selectCurrentMusicDic objectForKey:@"fileName"]];
            NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
            BOOL isExist = NO;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            if ([fileManager fileExistsAtPath:filePath]) {
                isExist = YES;
            }
            if (self.mainPlayer) {
                //后台存在播放器
                AVPlayer *mainPlayer = (AVPlayer *)self.mainPlayer;
                [mainPlayer pause];
                NSString *urlString = filePath;
                NSURL *urlPath = [NSURL fileURLWithPath:urlString];
                if (!isExist) {
                    urlString = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"url"]];
                    urlPath = [NSURL URLWithString:urlString];
                }
                AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
                [mainPlayer replaceCurrentItemWithPlayerItem:item];
                [mainPlayer play];
                
                //列入最近播放
                NSString *idStr = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"fileID"]];
                if (idStr.length > 0) {
                    FMManageObject *manager = [FMManageObject standerDefault];
                    NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                    if (arrs.count == 0) {
                        //来吧
                        NSString *name = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"fileName"]];
                        [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"size"]] withType:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"type"]]];
                    }
                }
            } else {
                //设置播放
                NSString *urlString = filePath;
                NSURL *urlPath = [NSURL fileURLWithPath:urlString];
                if (!isExist) {
                    urlString = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"url"]];
                    urlPath = [NSURL URLWithString:urlString];
                }
                AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
                AVPlayer *audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
                [audioPlayer play];
                [self setMainPlayer:audioPlayer];
                
                //列入最近播放
                NSString *idStr = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"fileID"]];
                if (idStr.length > 0) {
                    FMManageObject *manager = [FMManageObject standerDefault];
                    NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                    if (arrs.count == 0) {
                        //来吧
                        NSString *name = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"fileName"]];
                        [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"size"]] withType:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"type"]]];
                    }
                }
            }
            
        } else {
            //接口请求模式
            if(![_selectCurrentMusicDic.allKeys containsObject:@"AudioPath"]) return;
//            if ([[_selectCurrentMusicDic objectForKey:@"AudioStatus"] intValue] == 0) return;
            
            if (self.mainPlayer) {
                //后台存在播放器
                AVPlayer *mainPlayer = (AVPlayer *)self.mainPlayer;
                [mainPlayer pause];
                NSString *urlString = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_selectCurrentMusicDic objectForKey:@"AudioPath"]];
                NSURL *urlPath = [NSURL URLWithString:urlString];
                AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
                [mainPlayer replaceCurrentItemWithPlayerItem:item];
                [mainPlayer play];
                
                //列入最近播放
                NSString *idStr = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]];
                if (idStr.length > 0) {
                    FMManageObject *manager = [FMManageObject standerDefault];
                    NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                    if (arrs.count == 0) {
                        //来吧
                        NSString *audioName = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"AudioName"]];
                        NSArray *audioArr = [audioName componentsSeparatedByString:@"."];
                        NSString *name = audioArr[0];
                        [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@M",[_selectCurrentMusicDic objectForKey:@"Capacity"]] withType:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ValueID"]]];
                    }
                }
            } else {
                //设置播放
                NSString *urlString = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[_selectCurrentMusicDic objectForKey:@"AudioPath"]];
                NSURL *urlPath = [NSURL URLWithString:urlString];
                AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
                AVPlayer *audioPlayer = [[AVPlayer alloc]initWithPlayerItem:item];
                [audioPlayer play];
                [self setMainPlayer:audioPlayer];
                
                //列入最近播放
                NSString *idStr = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ID"]];
                if (idStr.length > 0) {
                    FMManageObject *manager = [FMManageObject standerDefault];
                    NSArray *arrs = [manager SelectTableByMusicPlayForRecentWithContentID:[NSString stringWithFormat:@"%@",idStr]];
                    if (arrs.count == 0) {
                        //来吧
                        NSString *audioName = [NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"AudioName"]];
                        NSArray *audioArr = [audioName componentsSeparatedByString:@"."];
                        NSString *name = audioArr[0];
                        [manager insertTableMusicPlayForRecentWithId:@"1" withFileName:name withFileID:idStr withUrl:urlString withSize:[NSString stringWithFormat:@"%@M",[_selectCurrentMusicDic objectForKey:@"Capacity"]] withType:[NSString stringWithFormat:@"%@",[_selectCurrentMusicDic objectForKey:@"ValueID"]]];
                    }
                }
            }
            
            //下载歌词
            NSString *lrcString =[_selectCurrentMusicDic objectForKey:@"LyricPath"];
            if (![lrcString isKindOfClass:[NSNull class]]) {
                lrcString =[NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,lrcString];
                [[DownLRCManager staredInstance]downloadWithUrl:lrcString withMusicName:[_selectCurrentMusicDic objectForKey:@"AudioName"]];
            }
        }

    }
    
    //属性设置
    if (self.audioPlayerType != AudioPLayerType_YinPin) {
        [self setIsPlaying:YES];
        [self setAudioPlayerType:AudioPLayerType_YinPin];
    } else {
        [self setIsPlaying:YES];
    }
    [self setIsBackPlay:YES];
  
    [[NSNotificationCenter defaultCenter]postNotificationName:@"AUDIO_PLAYER" object:nil];
    
    //播放列表
    if (musicPlayType != self.musicPlayType) {
        [self.musicArr removeAllObjects];
    }
//    NSMutableArray *musicMutArr = self.musicArr;
//    if (musicMutArr.count > 0) {
        //歌曲类型
        if (self.musicPlayType != musicPlayType || self.musicPlayType == MusicPLayType_DaJiaDouZaiTing || self.musicPlayType == MusicPLayType_AlbumList || self.musicPlayType == MusicPLayType_Online || self.musicPlayType == MusicPLayType_DownedMusic) {
            [self.musicArr removeAllObjects];
        }
        
        if (musicPlayType == MusicPLayType_RecentMusicPlay
            || musicPlayType == MusicPLayType_DownedMusic
           ) {
            NSMutableArray *mutArr = [[NSMutableArray alloc]initWithCapacity:musciArr.count];
            for (NSDictionary *dic in musciArr) {
                NSString *url = [dic objectForKey:@"url"];
                NSString *path = @"";
                if ([url rangeOfString:MUSIC_PLAY_Url].location != NSNotFound) {
                    path = [url substringWithRange:NSMakeRange([MUSIC_PLAY_Url length], url.length - [MUSIC_PLAY_Url length])];
                }
                
                NSString *fileName = [NSString stringWithFormat:@"%@.mp3",[dic objectForKey:@"fileName"]];
                NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
                BOOL isExist = NO;
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:filePath]) {
                    isExist = YES;
                }
                
                Music *music = [[Music alloc]init];
                music.name = [dic objectForKey:@"fileName"];
                music.type = @"mp3";
                music.urlPath = url;
                music.isCacheData = isExist;
                music.ID = [dic objectForKey:@"fileID"];
                music.AudioPath = path;
                music.LyricPath = @"";
                music.Capacity = [NSString stringWithFormat:@"%@",[dic objectForKey:@"size"]];
                music.AudioStatus = @"1";
                [mutArr addObject:music];
            }
            [self.musicArr addObjectsFromArray:mutArr];
        }
        else  if ( musicPlayType == MusicPLayType_ErGe
                  || musicPlayType == MusicPLayType_GuoXue
                  || musicPlayType == MusicPLayType_GuShi
                  || musicPlayType == MusicPLayType_English) {
            NSMutableArray *mutArr = [[NSMutableArray alloc]initWithCapacity:musciArr.count];
            for (NSDictionary *dic in musciArr) {
                NSString *url = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[dic objectForKey:@"AudioPath"]];
                NSString *path = @"";
                if ([url rangeOfString:MUSIC_PLAY_Url].location != NSNotFound) {
                    path = [url substringWithRange:NSMakeRange([MUSIC_PLAY_Url length], url.length - [MUSIC_PLAY_Url length])];
                }
                
                NSString *fileName = [NSString stringWithFormat:@"%@",[dic objectForKey:@"AudioName"]];
                if ([[fileName componentsSeparatedByString:@"."]count] == 2) {
                    fileName = [[fileName componentsSeparatedByString:@"."] firstObject];
                }
                NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
                BOOL isExist = NO;
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:filePath]) {
                    isExist = YES;
                }
                
                NSString *lrcPath = [dic objectForKey:@"LyricPath"];
                if ([lrcPath isKindOfClass:[NSNull class]]) {
                    lrcPath = @"";
                } else {
                    lrcPath = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,lrcPath];
                }
                
                NSString *Singer = [dic objectForKey:@"Singer"];
                if ([Singer isKindOfClass:[NSNull class]]) {
                    Singer = @"";
                }
                                     
                Music *music = [[Music alloc]init];
                music.name = fileName;
                music.type = [[[dic objectForKey:@"AudioPath"] componentsSeparatedByString:@"."]lastObject];
                music.urlPath = url;
                music.isCacheData = isExist;
                music.ID = [dic objectForKey:@"ID"];
                music.AudioPath = path;
                music.LyricPath = lrcPath;
                music.Capacity = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Capacity"]];
                music.AudioStatus = @"1";
                music.musicType = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ValueID"]];
                music.Singer = Singer;
                [mutArr addObject:music];
            }
            [self.musicArr addObjectsFromArray:mutArr];
        }
        else if (musicPlayType == MusicPLayType_DowningMusic) {
            //正在下载
            NSMutableArray *mutArr = [[NSMutableArray alloc]initWithCapacity:musciArr.count];
            for (DownMusicModel *musicModel in musciArr) {
                NSString *url = musicModel.url;
                NSString *path = @"";
                if ([url rangeOfString:MUSIC_PLAY_Url].location != NSNotFound) {
                    path = [url substringWithRange:NSMakeRange([MUSIC_PLAY_Url length], url.length - [MUSIC_PLAY_Url length])];
                }
                
                NSString *fileName = [NSString stringWithFormat:@"%@.mp3",musicModel.fileName];
                NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
                BOOL isExist = NO;
                NSFileManager *fileManager = [NSFileManager defaultManager];
                if ([fileManager fileExistsAtPath:filePath]) {
                    isExist = YES;
                }
                
                Music *music = [[Music alloc]init];
                music.name = musicModel.fileName;
                music.type = @"mp3";
                music.urlPath = url;
                music.isCacheData = isExist;
                music.ID = musicModel.musicID;
                music.AudioPath = path;
                music.LyricPath = @"";
                music.Capacity = [NSString stringWithFormat:@"%@",musicModel.totalSize];
                music.AudioStatus = @"1";
                [mutArr addObject:music];
            }
            [self.musicArr addObjectsFromArray:mutArr];
        }
        else {
            NSArray *musilAlbumArr = [self onTurnArrayFormArray:musciArr];
            [self.musicArr addObjectsFromArray:musilAlbumArr];
        }
     
//    }
//    else {
//        self.musicArr = [self onTurnArrayFormArray:musciArr];
//    }
    self.selectMusicIndex = selectIndex;
    self.musicPlayType = musicPlayType;
}

//转换成Music类型数组
- (NSMutableArray *)onTurnArrayFormArray:(NSArray *)musicArr
{
    NSMutableArray  *musciMutArr = [[NSMutableArray alloc]initWithCapacity:musicArr.count];
    for (NSDictionary *dic in musicArr) {
        NSString *audioName = [dic objectForKey:@"AudioName"];
        NSArray *audioArr = [audioName componentsSeparatedByString:@"."];
        NSString *name = audioArr[0];
        NSString *type;
        if (audioArr.count == 2) {
            type = audioArr[1];
        } else {
            type = @"mp3";
        }
        
        NSString *path = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,[dic objectForKey:@"AudioPath"]];
        BOOL isCacheData = NO;
        NSFileManager *fileManager = [[NSFileManager alloc]init];
        NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",audioName]];
        if ([fileManager fileExistsAtPath:filePath]) {
            isCacheData = YES;
        }
        
        NSString *Singer = [dic objectForKey:@"Singer"];
        if ([Singer isKindOfClass:[NSNull class]]) {
            Singer = @"";
        }
        
        Music *music = [[Music alloc]init];
        music.name = name;
        music.type = type;
        music.urlPath = path;
        music.isCacheData = isCacheData;
        if ([dic.allKeys containsObject:@"AudioID"]) {
            //电台跳入
            music.ID = [dic objectForKey:@"AudioID"];
        } else {
            music.ID = [dic objectForKey:@"ID"];
        }
        music.AudioPath = [dic objectForKey:@"AudioPath"];
        music.LyricPath = [dic objectForKey:@"LyricPath"];
        music.Capacity = [NSString stringWithFormat:@"%@M",[dic objectForKey:@"Capacity"]];
        music.AudioStatus = [dic objectForKey:@"AudioStatus"];
        music.musicType = [NSString stringWithFormat:@"%@",[dic objectForKey:@"ValueID"]];
        music.Singer = Singer;
        [musciMutArr addObject:music];
    }
    
    return musciMutArr;
}

- (NSMutableArray *)onTurnArrayFormQingZiXiuArray:(NSArray *)musicArr
{
    NSMutableArray  *musciMutArr = [[NSMutableArray alloc]initWithCapacity:musicArr.count];
    for (NSDictionary *dic in musicArr) {
        NSString *name = [dic objectForKey:@"ShowTitle"];
        NSString *type;
        NSString *path;
        NSString *fileType = [dic objectForKey:@"FilePath"];
        if ([fileType isKindOfClass:[NSNull class]]) {
            path = @"";
        } else {
            
            NSArray *audioArr = [fileType componentsSeparatedByString:@"."];
            type = [audioArr lastObject];
            if (type.length > 0) {
                
            } else {
                type = @"mp3";
            }
            path = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,fileType];
        }
        
        BOOL isCacheData = NO;
        NSFileManager *fileManager = [[NSFileManager alloc]init];
        NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]];
        if ([fileManager fileExistsAtPath:filePath]) {
            isCacheData = YES;
        }

        NSString *musicType = @"5";
        NSString *showType = [dic objectForKey:@"ShowType"];
        if ([showType intValue] == 1) {
            musicType = @"5";//宝贝秀
        }
        else {
            musicType = @"6";//主播秀
        }
        
        Music *music = [[Music alloc]init];
        music.name = name;
        music.type = type;
        music.urlPath = path;
        music.isCacheData = isCacheData;
        music.ID = [dic objectForKey:@"ID"];
        music.AudioPath = fileType;
        music.AudioStatus = [dic objectForKey:@"ShowStatus"];
        music.LyricPath = @"";
        music.Capacity = [NSString stringWithFormat:@"%@M",[dic objectForKey:@"Capacity"]];
        music.musicType = musicType;
        music.Sentiment = [NSString stringWithFormat:@"%@",[dic objectForKey:@"Sentiment"]];
        NSString *covpath = [dic objectForKey:@"CoverPath"];
        if ([covpath isKindOfClass:[NSNull class]]) {
            music.CoverPath = @"";
        } else {
            music.CoverPath = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,covpath];
        }
        [musciMutArr addObject:music];
    }
    
    return musciMutArr;
}

-(NSMutableArray*)onTurnArrayFormOnLineArray:(NSArray *)musicArr{
    NSMutableArray  *musciMutArr = [[NSMutableArray alloc]initWithCapacity:musicArr.count];
    for (NSDictionary *dic in musicArr) {
        NSString *name = [dic objectForKey:@"AudioName"];
        NSString *type;
        NSString *path;
        NSString*LyricPath=[dic objectForKey:@"LyricPath"];
        NSString *fileType = [dic objectForKey:@"AudioPath"];
        if ([fileType isKindOfClass:[NSNull class]]) {
            path = @"";
        } else {
            
            NSArray *audioArr = [fileType componentsSeparatedByString:@"."];
            type = [audioArr lastObject];
            if (type.length > 0) {
                
            } else {
                type = @"mp3";
            }
            path = [NSString stringWithFormat:@"%@%@",MUSIC_PLAY_Url,fileType];
        }
        
        BOOL isCacheData = NO;
        
        
        Music *music = [[Music alloc]init];
        music.name = name;
        music.type = type;
        music.urlPath = path;
        music.isCacheData = isCacheData;
        music.ID = [dic objectForKey:@"ID"];
        music.AudioPath = fileType;
        music.LyricPath=LyricPath;
        music.AudioStatus = [dic objectForKey:@"AudioStatus"];
        [musciMutArr addObject:music];
    }
    
    return musciMutArr;
}

#pragma mark -远程控制
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                [_mainPlayer pause];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
//                [self onSelectNextPlaying];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
//                [self onSelectLastPlaying];
                break;
            case UIEventSubtypeRemoteControlPause:
                
                [_mainPlayer pause];
                break;
            case UIEventSubtypeRemoteControlPlay:
                [_mainPlayer play];
                break;
            default:
                break;
        }
    }
}

#pragma mark -转化成mp3
- (void)transformCAFToMP3WithPath:(NSString *)filePath withNormalName:(NSString *)normal withFileName:(NSString *)fileName WithComplate:(void(^)(void))block withFaild:(void(^)(void))faile{
    
    if (filePath.length == 0) {
        if (faile) {
            faile();
        }
        return;
    }
   
    NSString *recordUrl = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.caf",normal]];
    NSString *mp3FilePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",normal]];
    
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    if (![fileManager fileExistsAtPath:recordUrl]) {
        NSLog(@"文件不存在!!!!");
        if (faile) {
            faile();
        }
        return;
    }
    
    @try {
        int read, write;
        
        FILE *pcm = fopen([recordUrl cStringUsingEncoding:1], "rb");   //source 被转换的音频文件位置
        fseek(pcm, 4*1024, SEEK_CUR);                                                   //skip file header
        FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 11025.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception description]);
    }
    @finally {
        
        NSLog(@"MP3生成成功: %@",mp3FilePath);
        if ([fileManager fileExistsAtPath:mp3FilePath]) {
            NSLog(@"文件存在!!!!");
           
//            BOOL isCopy = [fileManager copyItemAtPath:mp3FilePath toPath:mp3NewFilePath error:&error];
//            if (isCopy) {
//                 [fileManager removeItemAtPath:recordUrl error:nil];
            if (block) {
                block();
            }
        } else {
            if (faile) {
                faile();
            }
        }
    }
}

@end
